<?php

/**
 * @author Tongle Xu <xutongle@gmail.com>
 * @copyright Copyright (c) 2003-2103 Jinan TintSoft development co., LTD
 * @license http://www.tintsoft.com/html/about/copyright/
 * @version $Id$
 */
namespace Leaps\Console\Controller;

use Leaps;
use Leaps\Console\Controller;
use Leaps\Console\Exception;
use Leaps\Caching\Cache;

/**
 * 此命令允许您刷新缓存。
 *
 * @author Tongle Xu <xutongle@gmail.com>
 * @since 4.0
 */
class CacheController extends Controller {
	/**
	 * 列出可以刷新缓存。
	 */
	public function indexAction() {
		$caches = [ ];
		$components = Leaps::$app->getComponents ();
		foreach ( $components as $name => $component ) {
			if ($component instanceof Cache) {
				$caches [$name] = get_class ( $component );
			} elseif (is_array ( $component ) && isset ( $component ['class'] ) && strpos ( $component ['class'], 'Cache' ) !== false) {
				$caches [$name] = $component ['class'];
			}
		}
		if (! empty ( $caches )) {
			echo "The following caches can be flushed:\n\n";
			foreach ( $caches as $name => $class ) {
				echo " * $name: $class\n";
			}
		} else {
			echo "No cache is used.\n";
		}
	}

	/**
	 * 刷新缓存。
	 *
	 * @param string $component 缓存应用程序组件使用的名称。
	 *
	 * @throws \Leaps\Console\Exception
	 */
	public function flushAction($component = 'cache') {
		/**
		 * @var Cache $cache
		 */
		$cache = Leaps::$app->getComponent ( $component );
		if (! $cache || ! $cache instanceof Cache) {
			throw new Exception ( 'Application component "' . $component . '" is not defined or not a cache.' );
		}

		if (! $cache->flush ()) {
			throw new Exception ( 'Unable to flush cache.' );
		}

		echo "\nDone.\n";
	}
}
